package org.goldfish.distributed_framework.registry.handlers;

import com.sun.net.httpserver.HttpExchange;
import org.goldfish.distributed_framework.registry.ServiceRegistry;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.Collection;
import java.util.Collections;
import java.util.List;

public class QueryHandler extends BaseHandler {


    public QueryHandler(String pattern) {
        super(pattern);
    }

    @Override
    protected void doHandle(HttpExchange exchange, String extractedBody) throws IOException {
        if (!"GET".equals(exchange.getRequestMethod())) {
            sendResponse(exchange, 405, "Method Not Allowed");
            return;
        }

        String query = exchange.getRequestURI().getQuery();
        String service = null;

        if (query != null) {
            for (String param : query.split("&")) {
                String[] kv = param.split("=");
                if (kv.length == 2 && kv[0].equals("service")) {
                    service = kv[1];
                }
            }
        }

        System.out.println("查询请求解析的服务名: " + service);

        if (service != null) {
            // 获取服务地址列表并响应
            Collection<String> list = ServiceRegistry.query(service);
            if (!list.isEmpty()) {
                sendResponse(exchange, 200, String.join(",", list));
            } else {
                sendResponse(exchange, 404, "Service not found");
            }
        } else {
            sendResponse(exchange, 400, "Missing service param");
        }
    }
}
